﻿$(function() {
    var VcompanyType = $("#hd_companyType").val();
    var Vmode = $("#hd_mode").val();
    if (parseInt(VcompanyType) == 1) {
        $("li[id*='mode_']").hide();
        $("div[id*='order_mode_']").hide();
        $("#order_mode_2").show();
        $("#mode_2").show();
        $("#mode_2").addClass('onoff');
        $("#span_mode").html("食材下单");
        $("#spantitle").html("周价菜单");
        $("#div_all").hide();
        $("#div_tj").hide();
    }
    else {
        $("li[id*='mode_']").addClass('off');
        $("#mode_" + Vmode).removeClass('off').addClass('on');
        $("div[id*='order_mode_']").hide();
        $("#order_mode_" + Vmode).show();
        $("#div_all").show();
        $("#div_tj").show(); 
    }
});


tabMenu = function(id) {
   var VcompanyType=$("#hd_companyType").val();
   if(parseInt(VcompanyType)==0)
    {
        if (id == "mode_1") {
            $("#span_mode").html("菜谱下单");
        }
        else {
            $("#span_mode").html("食材下单");
            $(".ui-widget-content").css("height", "400px"); //重新载入高度

        }

        $("div[id*='order_mode_']").hide();
        $.each($("li[id^='mode_']"), function(i, n) {
            $(n).attr("class", "off");
        });
        $("#" + id).attr("class", "on");
        $("#order_" + id).show();
    }
};
function showProductDetails(obj, e) {
    var e = e || window.event;

    var current = $(obj);
    var offset = $(obj).offset();
    var x = offset.left + $(obj).width() + 0;
    var y = offset.top + $(obj).height() - 20;

    var w = $('#dvPanel').width();
    var h = $('#dvPanel').height();

    var ch = document.body.clientHeight;

    if (y + h > ch) {
        y = y + document.body.scrollTop - h + 60;
        $('.details_left').css('top', '300px');
    } else {
        $('.details_left').css('top', '5px');
    }

    $.ajax({
        url: 'product.ashx?Param=getdetail',
        data: 'productId=' + $(obj).attr('productId'),
        dataType: 'json',
        cache: true,
        async: true,
        success: function(jsonResult) {
            if (jsonResult) {
                $('#productName').text(jsonResult['productName']);
                var sourceImage = $(obj).attr('src') || $($(obj).parent().prev().find('img')[0]).attr('src');
                $('#productImage').attr('src', sourceImage);
                //$('#productImage').attr('src', jsonResult['productImage']);
                $('#productUnit').text(jsonResult['unit']);
                $('#productStandard').text(jsonResult['standard']);

                if ($(current).css('display') == 'inline') {
                    $("#dvPanel").css({ left: x + "px", top: y + "px" });
                    $("#dvPanel").show();
                }
            }
        }
    });
}
function hideProductDetaisl() {
    if ($('#dvPanel').is(':visible')) {
        $("#dvPanel").hide();
    }
}
$(document).ready(function() {
    $("#browser").treeview();
    if ($("ul>li", $('#marqueebox')).length > 1) {
    } else {
        $('#iconNotice').hide();
    }

    /*偏好设置订单列表*/
    $('#ddl_receiveDt').change(function() {
        var d = Date.parse($('#ddl_receiveDt').val());
        var week = d.getDay();
        week = (week == 0) ? 7 : week;
        var companyType = $("#hd_companyType").val();
        if (parseInt(companyType) == 0) {
            $.ajax({
                url: 'product.ashx',
                type: 'GET',
                data: 'Param=getFavouriteProducts&week=' + week,
                cache: false,
                dataType: 'json',
                success: function(json) {
                    if (json.length > 0) {
                        $("#hd_SelPros").val("");
                        var _html = new StringBuilder();
                        $(json).each(function(entryIndex, entry) {
                            _html.append(entry["productId"] + ",");
                            _html.append(entry["name"] + ",");
                            _html.append(entry["newprice"] + ",");
                            _html.append(entry["unit"] + ",1,0,");
                        });
                        var c = $("#hd_SelPros").val();
                        $("#hd_SelPros").val(c + _html.toString());
                        delAll();
                        loadJsonToHtml(json);
                    }
                },
                error: function(xhr, textStatus, errorThrown) {

                }
            });
        }
    });

    // 提前订单配送日期提示
    $('#ddl_receiveDt').change(function() {
        var wdays = Date.parse($("#hd_systemDate").val()); //得到当前礼拜日期
        var SelectWeekday = Date.parse($(this).val());
        var time = SelectWeekday.getTime() - wdays.getTime();
        var days = parseInt(time / (1000 * 60 * 60 * 24));
        if (parseInt($("#hd_companyType").val()) == 0) {
            if (days >= 1) {
                confirm('提示：由于您选择的配送时间超过了当前时间2天，所以价格以配送前一天的价格为标准；详情请点击【订单管理】->【提前订单查询】查看详情.');
            }
        }
    });
});

function getProductByRecipe(obj) {
    if (obj.checked == true) {
        $($(obj).next().find("img")[0]).show();
        getRecipeId(obj.value);
    }
    else {
        $($(obj).next().find("img")[0]).hide();
        delRecipeId(obj.value)
    }
}

function delRecipeId(recipeId) {
    var str_selRecipe = $("#hd_SelRecipe").val();
    var newRecipe = "";
    var arr = str_selRecipe.split(",");
    for (var i = 0; i < arr.length - 1; i++) {
        if (arr[i] != recipeId) {
            newRecipe += arr[i] + ",";
        }
    }
    $("#hd_SelRecipe").val(newRecipe);
}

function getRecipeId(recipeId) {
    var str_selRecipe = $("#hd_SelRecipe").val();
    var newRecipe = "";
    var arr = str_selRecipe.split(",");
    newRecipe = recipeId + ",";
    for (var i = 0; i < arr.length - 1; i++) {
        if (arr[i] != recipeId) {
            newRecipe += arr[i] + ",";
        }
    }
    $("#hd_SelRecipe").val(newRecipe);
}

function chkReset() {
    $("#browser input").attr("checked", false);
    $("#browser img").hide();
    $("#hd_SelRecipe").val("");
}

var getListByRecipeList = function() {
    if ($("#hd_SelRecipe").val() != "") {
        $.ajax({
            url: 'product.ashx',
            type: 'GET',
            dataType: "json",
            data: { Param: "getProductPriceByRecepe", recepe: $("#hd_SelRecipe").val() },
            cache: false,
            success: function(json) {
                if (json.length > 0) {
                    loadJsonToHtml(json);
                } else {
                    // window.location = '/index.html';
                    alert("所选菜谱中的商品未在采购范围内,无法使用此菜谱");
                }
            }
        });
    }
    else {
        alert("您还没有选择菜谱!");
        return false;
    }
};

/*----------------------------------------------------------------------------*/

//点击
var callbackFunction = function(productId, natrue) {
    var userId = $("#hd_userid").val();
    if (userId != 0) {
        $.ajax({
            url: 'product.ashx',
            type: 'GET',
            dataType: "json",
            data: { Param: "getProductPrice", productId: productId, nature: natrue },
            cache: false,
            success: function(json) {
                if (json.length > 0) {
                    loadJsonToHtml(json);
                }
                else {
                    //window.location = '/index.html';
                    alert("无法选用此商品，该商品已下架或未供应");
                }
            }
        });
    }
    else {
        window.location.href = "/login.html";
    }
};
/**/

var callbackFunctionFixed = function(productId, natrue,fpid) {
    var userId = $("#hd_userid").val();
    if (userId != 0) {
        $.ajax({
            url: 'product.ashx',
            type: 'GET',
            dataType: "json",
            data: { Param: "getProductFixedPrice", productId: productId, nature: natrue,fpid:fpid },
            cache: false,
            success: function(json) {
                if (json.length > 0) {
                    loadJsonToHtml(json);
                }
                else {
                    //window.location = '/index.html';
                    alert("无法选用此商品，该商品已下架或未供应");
                }
            }
        });
    }
    else {
        window.location.href = "/login.html";
    }
  };

//加载动态生成 HTML
function loadJsonToHtml(json) {
    $(json).each(function(entryIndex, entry) {
        if (!saveToHidden(entry["productId"], entry["name"], entry["newprice"], entry["unit"], entry["systemName"], entry["isCurrentPrice"], entry["bookamount"], '', entry['remarks'], entry['sellerId'], entry['sellerPrice'], entry['businessNature'])) {
            var _html = [];
            var price = parseInt(entry["isCurrentPrice"]) == 1 ? "<font color='red'>时价</font>" : Math.round(entry["newprice"] * 100) / 100;
            var remark = entry['remarks'].replace(/(^\s*)|(\s*$)/g, "") == "" ? "" : entry['remarks'];
            var bookAmount = entry['bookamount'] == "" ? "1" : entry['bookamount'];
            //_html.push('<table id="tmpproducts" width="97%" border="0" cellspacing="0" cellpadding="0" style="margin-buttom:8px;">');
            _html.push('<tr>');
            _html.push('<td style="width:5%;text-align:left; padding-left:5px;padding-top:5px;">');
            _html.push('<img  class="img viewImage01" onmouseover="showProductDetails(this,event);" onmouseout="hideProductDetaisl();" productId=' + entry["productId"] + ' style="width:20px;height:20px;" valign="middle" alt="" src="/upload_files/thumbnail1/' + entry["systemName"] + '" /></td>');

            _html.push('<td style="width:25%;text-align:left; padding-left:5px;">');
            _html.push('<a  class="viewImage"  onmouseover="showProductDetails(this,event);" onmouseout="hideProductDetaisl();"  href="javascript:void(0);" productId=' + entry["productId"] + ' price=' + entry["newprice"] + ' unit =' + entry["unit"] + '>' + entry["name"] + '</a>');
            _html.push('</td>');

            _html.push('<td style="width:10%;text-align:center;">');
            _html.push('<span id="sp_price_' + entry["productId"] + '">' + price + '</span>/' + entry["unit"] + '</td>');

            _html.push('<td style="width:15%;text-align:center;">');
            _html.push('<input onblur="checkNum(this);" onafterpaste="checkNum(this);" class="inputclass1"  maxlength="5" id="input_quantity_' + entry["productId"] + '_' + entry['businessNature'] + '" type="text" size="1" value="' + bookAmount + '" />');
            _html.push('<a class="blue" href="javascript:changeQuantity(' + entry["productId"] + ',' + entry['businessNature'] + ');">更新</a></td>');

            _html.push('<td style="width:30%;line-height:35px;text-align:right;">');
            _html.push('<input type="text" id="input_note' + entry["productId"] + '_' + entry['businessNature'] + '" value="' + remark + '" height="25" style="width:170px;" />&nbsp;</td>');

            _html.push('<td style="width:10%;text-align:right;">');
            _html.push('<img src="/app_common/images/delete.gif" alt="" onclick="deleteCurrent(this,' + entry["productId"] + ',' + Math.round(entry["newprice"] * 100) / 100 + ',' + entry["isCurrentPrice"] + ',' + entry['businessNature'] + ');"/>&nbsp;</td>');
            _html.push('</tr>');
            // _html.push('</table>');
            $('#tmpproducts').append(_html.join(''));
            if (parseInt(entry["isCurrentPrice"]) != 1)//判断不是时价,如果不是则执行下行代码
                CalculatePriceSum(Math.round(entry["newprice"] * 100) / 100, bookAmount, true);
            buildCrossStyle();

        }

    });

}


//点击
var callbackFunctionSpecials = function(productId) {
    var userId = $("#hd_userid").val();
    if (userId != 0) {
        $.ajax({
            url: 'product.ashx',
            type: 'GET',
            dataType: "json",
            data: { Param: "getSpecialsProduct", productId: productId },
            cache: false,
            success: function(json) {
                if (json.length > 0) {
                    loadJsonToHtml(json);
                }
                else {
                    //window.location = '/index.html';
                    alert("无法选用此商品，该商品已下架或未供应");
                }
            }
        });
    }
    else {
        window.location.href = "/login.html";
    }
};


/*保存值到隐藏控件*/
function saveToHidden(productId, name, Price, unit, systemName, isCurrentPrice, quantity, note, remarks, sellerid, sellerprice, businessNature) {
    var products = [];
    if ($('#hd_loadval').val().length > 0) {
        products = jsonParse($('#hd_loadval').val());
    }
    var isExists = false;
    $(products).each(function(entryIndex, entry) {
        if (parseInt(entry['productId']) == productId && parseInt(entry['businessNature']) == businessNature) {
            isExists = true;
            return false;
        }
    });
    if (!isExists) {
        var prices = isCurrentPrice == 0 ? Price : "0.00"; //判断如果是时价商品，刚单价为0
        var quantity = quantity == "" ? "1" : quantity;
        var product = { 'productId': parseInt(productId), 'name': name, 'Price': Math.round(prices * 100) / 100, 'unit': unit, 'quantity': quantity, 'note': note, 'systemName': systemName, 'isCurrentPrice': parseInt(isCurrentPrice), 'remarks': remarks, 'SellerId': sellerid, 'SellerPrice': sellerprice, 'businessNature': parseInt(businessNature) }; //生成订单的细目
        products.push(product);
        $('#hd_loadval').val(Object.serialize2Str(products));
        //alert($('#hd_loadval').val());
    }
    return isExists;
}


//得到总金额  (accMultiply(x,y）来自于javascript-float-plus.js)
function CalculatePriceSum(price, quantity, status) {

   // alert(price);
    var Sumspan_total = $("#span_total").html();

    if (Sumspan_total == "")
        Sumspan_total = 0;

    var newsSumprices = accMultiply(price, quantity);
    if (status == true)//代表相加
    {
        var sumPrice = parseFloat(Sumspan_total) + parseFloat(Math.round(newsSumprices * 100) / 100);
        $("#span_total").html(Math.round(sumPrice * 100) / 100);
    }
    else//相减
    {
        var sumPrice = parseFloat(Sumspan_total) - parseFloat(Math.round(newsSumprices * 100) / 100);
        $("#span_total").html(Math.round(sumPrice * 100) / 100);
    }
}


//样式
function buildCrossStyle() {
    $('#tmpproducts tr').each(function(entryIndex, entry) {
        if (entryIndex % 2 == 1) {
            $(entry).addClass('even');
        } else {
            if ($(entry).hasClass('even')) {
                $(entry).removeClass('even');
            }
        }
    });
}

//删除
function deleteCurrent(current, productId, price, isCurrentPrice, businessNature) {
    changeQuantity(productId, businessNature); //删除前更新数量
    if (deleteFromHidden(productId, businessNature)) {
        var objElement = $(current).parent().parent();
        var quantityunit = $("#input_quantity_" + productId + "_" + businessNature).val();

        if (parseInt(isCurrentPrice) != 1)//判断是否为时价
            CalculatePriceSum(price, parseFloat(quantityunit), false);

        objElement.remove();
        buildCrossStyle();
    }
}

//更新JSON
function deleteFromHidden(productId, businessNature) {
    var products = [];
    if ($('#hd_loadval').val().length > 0) {
        products = jsonParse($('#hd_loadval').val());
        var isDeleted = false;

        for (var k = 0; k <= products.length; k++) {
            if (products[k]['productId'] == productId && products[k]['businessNature'] == businessNature) {
                delete products[k];
                isDeleted = true;
                break;
            }
        }

        if (isDeleted) {
            $('#hd_loadval').val(Object.serialize2Str(products));
        }

        return isDeleted;
    }
    return false;
}



// 数量
function changeQuantity(productId, businessNature) {
    var quanTxt = $("#input_quantity_" + productId + "_" + businessNature).val();
    var products = [];
    if ($('#hd_loadval').val().length > 0) {
        products = jsonParse($('#hd_loadval').val());
    }
    $(products).each(function(entrtyIndex, entrty) {
        if (parseInt(entrty['productId']) == productId && entrty['businessNature'] == businessNature) {
            var Sumspan_total = $("#span_total").html();
            if (parseInt(entrty["isCurrentPrice"]) != 1)//判断不是时价,如果不是则执行下行代码
            {
                var oldMoney = accMultiply(parseFloat(entrty['Price']), parseFloat(entrty["quantity"])); //当得到当前修改对象原的金额
                Sumspan_total = parseFloat(Sumspan_total) - Math.round(parseFloat(oldMoney)*100)/100;
                $("#span_total").html(Sumspan_total); //减去原有的值
                CalculatePriceSum(entrty['Price'], quanTxt, true); //更新最后的价格
            }
            entrty["quantity"] = parseFloat(quanTxt); //修改该数量
            //alert(entrty["quantity"]);

        }
    })
    $('#hd_loadval').val(Object.serialize2Str(products));
}



//确认提交
function comfirmOrder() {
    var jsonLoad = [];
    if ($("#hd_loadval").val() != "")
        jsonLoad = jsonParse($("#hd_loadval").val()).length; //序列化json对象数组，判断数组的长度
    if (jsonLoad != 0) {
           if($("#ddl_receiveDt").val()!=null)
           {
                var wdays = Date.parse($("#hd_systemDate").val()); //得到当前礼拜日期
                var SelectWeekday = Date.parse($("#ddl_receiveDt").val());
                var time = SelectWeekday.getTime() - wdays.getTime();
                var days = parseInt(time / (1000 * 60 * 60 * 24));
                
                var predicationDict = ["明天","后天","本周","下周","下下周"];
                var weekdayArry=["日","一","二","三","四","五","六"];
                
                var currentWeek1 = SelectWeekday.getDay(); 
                if ( currentWeek1 == 0 ) {currentWeek1 = 7; } 
                var selectSunday=SelectWeekday.getTime() + (7-currentWeek1)*24*60*60*1000;//所选日期该周的礼拜天
                selectSunday=new Date(selectSunday);
                
                var week1=getWeeks(wdays);
                var week2=getWeeks(SelectWeekday);
                var Intweeks=parseInt(week2)-parseInt(week1);//判断是否在同一周
                
                var messages="请确认您的配送时间，您当前选择配送日期是：";
                var messSelectWeek="("+$("#ddl_receiveDt").val()+")";
                var getdays=SelectWeekday.getDay();//当天礼拜几
                if(Intweeks>0)
                {
                    messages+=predicationDict[Intweeks+2]+weekdayArry[parseInt(getdays)]+messSelectWeek;
                }
                else//本周
                {
                     if(days<=1)
                     {
                        messages+=predicationDict[parseInt(days)]+messSelectWeek;
                     }
                     else
                     {
                        messages+=predicationDict[2]+weekdayArry[parseInt(getdays)]+messSelectWeek;
                     }
                }
                
                $('#receiveDtConfirm').find('b').text(messages);
                $('#receiveDtConfirm').dialog('open');
                return false;
       }
        else
        {
        alert("您当前无法选择配送日期，请联系后台管理人员，不能提交订单！");
        }
    }
    else {
        alert("您还没有选择商品，不能提交订单！");
    }
}

$(function(){
    $('#receiveDtConfirm').dialog({
        autoOpen:false,
        modal:true,
        width:510,
        buttons:{
            '确定':function(){
                $(this).dialog('close');
                ChangeNoto();
                $("#threeColPanel").hide();
                $("#div_4").show();
                getOrderItem_new();
            },
            '取消':function(){
                $(this).dialog('close');
            }
        }
    });
    
    $('#divMutilCompany').dialog({
        autoOpen:false,
        modal:true,
        width:510,
        buttons:{
            '确定':function(){
                $(this).dialog('close');
            },
            '取消':function(){
                $(this).dialog('close');
            }
        }
    });
});

//根据日期判断第几周
var getWeeks = function(dateNow) {
    var date = new Date(dateNow);
    var year = date.getYear();
    var mouth = date.getMonth();
    var day = date.getDate();
    var day1 = new Date(year, mouth, day);
    var day2 = new Date(year, 0, 1);

    var firstweek = day2.getDay();//1月1日是星期几
    if(firstweek == 0) {
    firstweek = 6;
    }else {
    firstweek = firstweek - 1;
    }//转化为0表示星期一,6表示星期日
    firstweek = (7 - firstweek) % 7;//计算1月1日离第一周的天数
    var day3 = new Date(year, 0, 1+firstweek)
    var result = Math.round((day1.getTime() - day3.getTime())/(1000*60*60*24));
    result = Math.floor(result / 7)+1;//这个地方应该用floor返回最小次数然后+1
    return result;
};


function CheckWeekTime() {
    var weekBool = false;
    var wdays = Date.parse($("#hd_systemDate").val()); //得到当前礼拜日期
    var SelectWeekday = Date.parse($("#ddl_receiveDt").val());
    var time = SelectWeekday.getTime() - wdays.getTime();
    var days = parseInt(time / (1000 * 60 * 60 * 24));
    if (wdays.getDay() == 5) {
        if (days <= 2) {
            weekBool = true;
        }
    }
    else if (wdays.getDay() == 6) {
        if (days <= 1) {
            weekBool = true;
        }
    }
    else {
        if (days == 0) {
            weekBool = true;
        }
    }
    return true;

    //第二种
    //var date2 = new Date(systemDate.getFullYear(), 0, 1);
    //var d = Math.round((systemDate.valueOf() - date2.valueOf()) / 86400000);
    //var d1=Math.round((selectedDate.valueOf()-date2.valueOf()) / 86400000);

    // if(parseInt(currentWeekday)==5)//判断是否为礼拜五
    // {
    //	allowOrder=(d1-d<=3);
    // }
    // else
    // {
    //	allowOrder=(d1-d<=1);
    // }

    //return allowOrder;
}



//确认订单前要将[备注内容] [商品数量]同时更新写入指定的JSON对象中

function ChangeNoto() {
    var products = [];
    var sumMony = 0;
    if ($('#hd_loadval').val().length > 0) {
        products = jsonParse($('#hd_loadval').val());
    }
    $(products).each(function(entrtyIndex, entrty) {

        var noteTxt = $("#input_note" + parseInt(entrty['productId']) + "_" + entrty['businessNature']).val(); //备注
        var quanTxt = $("#input_quantity_" + parseInt(entrty['productId']) + "_" + entrty['businessNature']).val(); //数量
        entrty["note"] = noteTxt; //修改该备注
        entrty["quantity"] = parseFloat(quanTxt); //修改数量
        sumMony = sumMony + quantityPriceSum(parseInt(entrty['isCurrentPrice']), entrty['Price'], entrty['quantity']);
    });
    sumMony = Math.round(sumMony * 100) / 100;
    $('#hd_loadval').val(Object.serialize2Str(products)); //细目
    $("#span_total").html(sumMony) //总金额

}


//数量最后确认状态----------
function quantityPriceSum(isCurrentPrice, price, quantity) {
    var HiddSumMony = 0;
    if (isCurrentPrice != 1)//代表不是实价的商品
    {
        var newsSumprices = accMultiply(price, quantity);
        HiddSumMony = HiddSumMony + newsSumprices;
    }
    return Math.round(HiddSumMony*100)/100;
}

//填充列表OrderItem
function getOrderItem_new() {
    $('#tb_orderItem').html("");
    var products = [];
    var _html = [];
    var isCurrentPrice = 0;
    if ($('#hd_loadval').val().length > 0) {
        //alert($('#hd_loadval').val());
        products = jsonParse($('#hd_loadval').val());
    }
    $(products).each(function(entrtyIndex, entrty) {
        var price = parseInt(entrty["isCurrentPrice"]) == 1 ? "<font color='red'>时价</font>" : Math.round(entrty["Price"] * 100) / 100;
        if (isCurrentPrice == 0)
            isCurrentPrice = parseInt(entrty["isCurrentPrice"]);
        _html.push('<tr>');
        _html.push('<td width="30%">' + entrty["name"] + '</td>');
        _html.push('<td width="15%">' + price + '/' + entrty["unit"] + '</td>');
        _html.push('<td width="10%">' + entrty["quantity"] + '</td>');

        if (parseInt(entrty["isCurrentPrice"]) != 1) {
            _html.push('<td width="15%">' + Math.round(accMultiply(parseFloat(price), parseFloat(entrty["quantity"]))*100)/100 + '</td>');
           // _html.push('<td width="15%">' + accMultiply(parseFloat(price), parseFloat(entrty["quantity"]))+ '</td>');
        }
        else {
            _html.push('<td width="15%"><font color="red">时价</font></td>');
        }

        _html.push('<td width="320px" style="height:auto;text-align:left;">' + entrty["note"] + '</td>');
        _html.push('</tr>');
    })
    var amount = $("#span_total").html();
    _html.push('<tr><td colspan="3" align="right">总计</td>');
    _html.push('<td><font color="red">' + Math.round(amount * 100) / 100 + '</font></td>');
    _html.push('<td></td>');
    _html.push('</tr>');
    _html.push('<tr>');
    var msg = isCurrentPrice == 0 ? "" : "注：您当前订单中存在时价商品，订单总金额不为最终金额！";
    _html.push('<td colspan="5" align="right" style="color:Red">' + msg + '</td>');
    _html.push('</tr>');

    $("#hd_amount").val(Math.round(amount * 100) / 100);
    $("#sp_orderMsg").html($("#txt_orderNote").val());
    var psDt = $("#ddl_receiveDt").val();
    var psTime = $("#hd_psTime").val();
    $("#sp_psDt").html(psDt + "　" + psTime);
    $('#tb_orderItem').append(_html.join(''));

    tb_orderItemStyle();


}


function tb_orderItemStyle() {
    $('#tb_orderItem tr').each(function(entryIndex, entry) {
        if (entryIndex % 2 == 1) {
            $(entry).addClass('even');
        } else {
            if ($(entry).hasClass('even')) {
                $(entry).removeClass('even');
            }
        }
    });
}


//全删
function delAll() {
    $("#tmpproducts").html("");
    // $("#div_showSelectPro").html("");
    $("#hd_SelPros").val("");
    $("#span_total").html("0.00");
    $('#hd_loadval').val('');
    $("#txt_orderNote").html('');
}



//最后确认
function checkOrder() {
    var flag = $("#hd_isTester").val();
    if (flag == "1") {
        alert('测试账号不能提交订单');
        return false;
    }
    else {
        // 检查商品是否取消供应
        var arr = [];
        var pros = jsonParse($('#hd_loadval').val());
        var companyIds=$("#hd_companyType").val();//判断企业是否为周价企业
        
        $(pros).each(function(entrtyIndex, entrty) {
            arr.push(entrty["productId"]);
        });
        var isCheck = false;

        $.ajax({
            url: 'product.ashx',
            type: 'GET',
            data: 'Param=getsupplycancelproductlist&productIds=' + arr.join(','),
            async: false,
            cache: false,
            dataType: 'json',
            success: function(jsonResult) {
                if(parseInt(companyIds)==0) //不是周价企业则判断该商品是否销售，价格表中否存在供应商报价
                {
                    if (jsonResult.length > 0) {
                        var arrString = [];
                        $(jsonResult).each(function(entryIndex, entry) {
                            arrString.push(entry['productName']);
                        });

                        alert(arrString.join('\n'));
                    }
                    else {
                        isCheck = true;
                    }
                }
                else
                {
                    isCheck=true;
                }
            },
            error: function(xhr, textStatus, errorThrown) {
            }
        });
        return isCheck;
        $('#lbtn_Submit').attr('disabled', false);
    }
}



/*end-----------------------------------------------------------------------------------*/


function checkNum(obj) {
    var objvalue = parseFloat(obj.value);
    if (objvalue != "" && objvalue != 0) {
        var flag = IsNumeric(obj.value);
        if (!flag)
            obj.value = "1";
    }
    else
        obj.value = "1";
}
function IsNumeric(oNum) {
    //var strP = /^\d+(\.\d)?$/;
    var strP = /^\d+(\.\d{1,2})?$/;
    if (strP.test(oNum))
        return true;
    else
        return false;
}

//返回修改
function returnUpdate() {
    $("#threeColPanel").show();
    $("#div_4").hide();
    $("#div_5").hide();
}
function orderSuccess() {
    $("#threeColPanel").hide();
    $("#div_5").show();
}
function showOrderItem() {
    var id = $("#hd_orderid").val();
    // 提前订单查询
    var wdays = Date.parse($("#hd_systemDate").val()); //得到当前礼拜日期
    var SelectWeekday = Date.parse($("#ddl_receiveDt").val());
    var time = SelectWeekday.getTime() - wdays.getTime();
    var days = parseInt(time / (1000 * 60 * 60 * 24));
    var companyIds=$("#hd_companyType").val();//判断企业是否为周价企业

    if (days > 0 && parseInt(companyIds)==0) {
        window.location.href = "buyer_dynamicOrderItem" + id + ".html";
    } else {
        window.location.href = "buyer_orderItemList.html?order=" + id + "&type=1";
    }
}

function startmarquee(lh, speed, delay) {
    var p = false;
    var t;
    var sh;
    var o = document.getElementById("marqueebox");
    o.innerHTML += o.innerHTML;
    o.style.marginTop = 0;
    o.onmouseover = function() { p = true; }
    o.onmouseout = function() { p = false; }
    function start() {
        sh = o.offsetHeight;
        o.style.height = sh;
        t = setInterval(scrolling, speed);
        if (!p) o.style.marginTop = parseInt(o.style.marginTop) - 1 + "px";
    }
    function scrolling() {
        if (parseInt(o.style.marginTop) % lh != 0) {
            o.style.marginTop = parseInt(o.style.marginTop) - 1 + "px";
            if (Math.abs(parseInt(o.style.marginTop)) >= sh / 2) o.style.marginTop = 0;
        } else {
            clearInterval(t);
            setTimeout(start, delay);
        }
    }
    setTimeout(start, delay);
}


$(function(){

$("#accordion").accordion({ header: "h3",action:0 });//默认

var isTreePanelBoolen=false;
var treepanle3_id="TreePanel3";
var treepanle3_Container="TreePanel3_Container";
var treepanle3_url="buyer_GeneralProduct.ashx";
var treepanle1_id="TreePanel1";
var treepanle1_Container="TreePanel1_Container";
var treepanle1_url="buyer_ConventionalPrice.ashx";
var treepanle2_id="TreePanel2";
var treepanle2_Container="TreePanel2_Container";
var treepanle2_url="productSpecialsPrice.ashx";
$.ajax({
    url: 'buyer_BuyerRange.ashx',
    type: 'GET',
    dataType: "text",
    cache: false,
    success: function(json) {
      $("#accordion").accordion({ active:parseInt(json) });//根据采购商的采购范围设置accordion的显示索引号
      switch(parseInt(json))
      {
       case 0:
       //加载treepanle3
       Buyerrange(treepanle3_id,treepanle3_Container,treepanle3_url);
       isTreePanelBoolen=true;
       break;
       case 1:
        //加载treepanle1
        Buyerrange(treepanle1_id,treepanle1_Container,treepanle1_url);
       break;
      }
    }
    
});

//点击accordion触发事件
$("#accordion").accordion({
   changestart: function(event, ui) {
     var Vactive=$("#accordion").accordion("option", "active");
     switch(parseInt(Vactive))
      {
       case 0: 
       if(!isTreePanelBoolen)
       Buyerrange(treepanle3_id,treepanle3_Container,treepanle3_url);
       break;
       case 1:
        if($("#TreePanel1_Container").html().length==0)
        //加载treepanle1
        Buyerrange(treepanle1_id,treepanle1_Container,treepanle1_url);
       break;
       
       case 2:
       if($("#TreePanel2_Container").html().length==0)
        //加载treepanle2
        Buyerrange(treepanle2_id,treepanle2_Container,treepanle2_url);
       break;
      }
   }
});

//加载treepanle2
//Buyerrange(treepanle2_id,treepanle2_Container,treepanle2_url);
});

window.Buyerrange=function(id,renderTo,url)
{
    Ext.onReady(function(){
    new Coolite.Ext.TreePanel({
        id:id,
        renderTo:renderTo,
        width:228,
        height:460,
        title:"类别列表",
        header:false,
        collapseFirst:false,
        border:false,
        autoScroll:true,
        nodes:[{text:"所有类别",nodeType:"async",id:"0,0"}],
        rootVisible:false,
        loader:new Ext.tree.TreeLoader({requestMethod:"GET",url:url}),
        containerScroll:true
        });
    });
}